package com.market.controller;

import com.market.entity.Provider;
import com.market.service.ProviderService;
import com.market.utils.PageResult;
import com.market.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.market.entity.User;

@RestController
@RequestMapping("/provider")
public class ProviderController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProviderController.class);

    @Autowired
    private ProviderService providerService;
    
    /**
     * 获取所有供应商列表
     */
    @GetMapping("/list")
    public Map<String, Object> list() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Provider> providers = providerService.findAll();
            result.put("flag", true);
            result.put("data", providers);
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取供应商列表失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 分页查询供应商
     */
    @GetMapping("/search")
    public Map<String, Object> search(
            @RequestParam(required = false) String proName,
            @RequestParam(required = false) String proCode,
            @RequestParam(required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        try {
            PageResult<Provider> pageResult = providerService.findByPage(proName, proCode, currentPage, pageSize);
            
            result.put("flag", true);
            result.put("data", pageResult.getList());
            result.put("total", pageResult.getTotalCount());
            result.put("currentPage", pageResult.getCurrentPage());
            result.put("pageSize", pageResult.getPageSize());
            result.put("totalPages", pageResult.getTotalPages());
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "搜索供应商失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 根据ID获取供应商详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Provider provider = providerService.findById(id);
            if (provider != null) {
                result.put("flag", true);
                result.put("data", provider);
            } else {
                result.put("flag", false);
                result.put("message", "未找到ID为" + id + "的供应商");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取供应商详情失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 添加供应商
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Provider provider, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        // 验证字段长度
        if (provider.getProCode() != null && provider.getProCode().length() > 20) {
            result.put("flag", false);
            result.put("message", "供应商编码不能超过20个字符");
            return result;
        }
        
        if (provider.getProName() != null && provider.getProName().length() > 20) {
            result.put("flag", false);
            result.put("message", "供应商名称不能超过20个字符");
            return result;
        }
        
        if (provider.getProDesc() != null && provider.getProDesc().length() > 50) {
            result.put("flag", false);
            result.put("message", "供应商描述不能超过50个字符");
            return result;
        }
        
        if (provider.getProContact() != null && provider.getProContact().length() > 20) {
            result.put("flag", false);
            result.put("message", "供应商联系人不能超过20个字符");
            return result;
        }
        
        if (provider.getProPhone() != null && provider.getProPhone().length() > 20) {
            result.put("flag", false);
            result.put("message", "联系电话不能超过20个字符");
            return result;
        }
        
        if (provider.getProAddress() != null && provider.getProAddress().length() > 50) {
            result.put("flag", false);
            result.put("message", "地址不能超过50个字符");
            return result;
        }
        
        if (provider.getProFax() != null && provider.getProFax().length() > 20) {
            result.put("flag", false);
            result.put("message", "传真不能超过20个字符");
            return result;
        }
        
        // 设置创建者为当前登录用户
        Long userId = SessionUtil.getCurrentUserId();
        if (userId != null) {
            provider.setCreatedBy(userId);
        }
        
        return providerService.add(provider);
    }
    
    /**
     * 修改供应商
     */
    @PostMapping("/update")
    public Map<String, Object> update(@RequestBody Provider provider, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 记录会话和请求信息（调试用）
            HttpSession session = request.getSession(false);
            if (session != null) {
                logger.info("当前session ID: {}", session.getId());
                User currentUser = (User) session.getAttribute(SessionUtil.USER_SESSION);
                if (currentUser != null) {
                    logger.info("从session中获取到用户: ID={}, 用户名={}", currentUser.getId(), currentUser.getUserName());
                    // 直接从session中获取当前用户ID设置为修改者
                    provider.setModifyBy(currentUser.getId());
                } else {
                    logger.warn("session中没有用户信息");
                }
            } else {
                logger.warn("当前请求没有关联的session");
            }
            
            // 验证字段长度
            if (provider.getProCode() != null && provider.getProCode().length() > 20) {
                result.put("flag", false);
                result.put("message", "供应商编码不能超过20个字符");
                return result;
            }
            
            if (provider.getProName() != null && provider.getProName().length() > 20) {
                result.put("flag", false);
                result.put("message", "供应商名称不能超过20个字符");
                return result;
            }
            
            if (provider.getProDesc() != null && provider.getProDesc().length() > 50) {
                result.put("flag", false);
                result.put("message", "供应商描述不能超过50个字符");
                return result;
            }
            
            if (provider.getProContact() != null && provider.getProContact().length() > 20) {
                result.put("flag", false);
                result.put("message", "供应商联系人不能超过20个字符");
                return result;
            }
            
            if (provider.getProPhone() != null && provider.getProPhone().length() > 20) {
                result.put("flag", false);
                result.put("message", "联系电话不能超过20个字符");
                return result;
            }
            
            if (provider.getProAddress() != null && provider.getProAddress().length() > 50) {
                result.put("flag", false);
                result.put("message", "地址不能超过50个字符");
                return result;
            }
            
            if (provider.getProFax() != null && provider.getProFax().length() > 20) {
                result.put("flag", false);
                result.put("message", "传真不能超过20个字符");
                return result;
            }
            
            // 设置修改者为当前登录用户
            // 如果之前从session获取成功，就不会覆盖已设置的值
            if (provider.getModifyBy() == null) {
                Long userId = SessionUtil.getCurrentUserId();
                logger.info("SessionUtil获取的当前用户ID: {}", userId);
                if (userId != null) {
                    provider.setModifyBy(userId);
                }
            }
            
            return providerService.update(provider);
        } catch (Exception e) {
            logger.error("更新供应商异常", e);
            result.put("flag", false);
            result.put("message", "更新供应商失败: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 删除供应商
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        return providerService.deleteById(id);
    }
}
